package com.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * BaseAtcion 基类
 * @author swp
 * 2016-12-7 09:14:35
 */
public class BaseAction implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private static Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,
			   new DateSerializerUtil()).registerTypeAdapter(Calendar.class,
			   new DateSerializerUtil()).registerTypeAdapter(GregorianCalendar.class,
			   new DateSerializerUtil())
			   .setDateFormat(DateFormat.LONG).setPrettyPrinting()
			   .create();
	
    /**
     * 输出json对象
     * @param baseResponse
     * @param obj
     */
    public void jsonOutPut(HttpServletResponse baseResponse,Object obj){
    	baseResponse.setHeader("Pragma", "No-cache");
    	baseResponse.setHeader("Cache-Control", "no-cache");
    	baseResponse.setCharacterEncoding("UTF-8");
    	baseResponse.setContentType("application/json;charset=UTF-8");  
        PrintWriter out = null;  
        try {
			out = baseResponse.getWriter();
	        String str = gson.toJson(obj);
	        out.println(str);
	        out.flush();  
	        out.close(); 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out!=null) {
				try {
					out.close();
				} catch (Exception e) {
				}
			}
		}
    }
    
    /**
     * 输出json字符串
     * @param baseResponse
     * @param str
     */
    public void basicOutPut(HttpServletResponse baseResponse,String str){
    	baseResponse.setHeader("Pragma", "No-cache");
		baseResponse.setHeader("Cache-Control", "no-cache");
		baseResponse.setCharacterEncoding("UTF-8");
    	baseResponse.setContentType("text/html;charset=UTF-8");  
    	PrintWriter out = null;  
    	try {
    		out = baseResponse.getWriter();
        	out.println(str);
        	out.flush();  
        	out.close(); 
    	} catch (IOException e) {
    		e.printStackTrace();
    	}  finally {
			if (out!=null) {
				try {
					out.close();
				} catch (Exception e) {
				}
			}
		}
    }
}
